from flask import Blueprint, make_response, jsonify, request,redirect
from tools.captcha.captcha import captcha
from tools.myredis import r
from tools.myjwt import mjwt
from tools.comm import sendMsg
import json, random,time,functools
from application.models.users.user import *

user_blue = Blueprint("userblue", __name__)


# def islogin(func):
#     @functools.wraps(func)
#     def wrapper():
#         func()
#         return func()
#     return wrapper

def islogin(type):
    def pemistion(func):
        @functools.wraps(func)
        def wrapper():
            func()
            if type == 1:
                return redirect("http://www.baidu.com")
            else:
                return redirect("http://www.jd.com")
        return wrapper
    return pemistion



# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    # 生成图片验证码
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid作为redis key
    uuid = str(request.args.get('uuid'))
    # 存入redis
    r.str_add(uuid, str(text), 60)
    # 以流的方式生成图形验证码
    res = make_response(image)
    res.headers['Content-Type'] = 'image/jpg'
    return res


@user_blue.route("/sendSmsCode", methods=['POST'])
def sendSmsCode():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        mobile = data['mobile']
        value = r.str_get(uuid)
        if value:
            if piccode.lower() == value.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({"code": 10012, "mes": '一分钟内不能重复发'})
                scode = random.randint(10000, 99999)
                print(scode)
                flag = sendMsg(mobile, scode)
                if flag == True:
                    r.str_add(mobile, scode, 60)
                    r.del_str(uuid)
                    return jsonify({"code": 200, 'mes': '发送成功'})
                else:
                    return jsonify({"code": 200, 'mes': '发送验证码失败'})
            else:
                return jsonify({"code": 10011, 'mes': '图片验证码错误'})
        else:
            return jsonify({"code": 10010, 'mes': '图片验证码不存在'})


@user_blue.route("/login",methods=['POST'])
def login():
    data  = request.data
    if data:
        data = json.loads(data)
        mcode = data['code']
        mobile = data['mobile']
        code = r.str_get(mobile)
        if code:
            if int(code) == int(mcode):
                user = User.query.filter(User.mobile == mobile).first()
                if user:
                    r.del_str(mobile)
                else:
                    u = User(mobile = mobile,nikename = mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                    token = mjwt.jwt_encdoe(data={"data":{'uid':user.id,'exp':int(time.time())}})
                return jsonify({"code":200,"token":token,'userid':user.id})
            else:
                return jsonify({"code":10021,'mes':'验证码错误'})
        else:
            return jsonify({"code":10020,'mes':''})


@user_blue.route("/cart",methods=['POST'])
def cart():
    pass